from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import ListView,CreateView,UpdateView,DeleteView
from .models import Grades
from django.db.models import Q
from .forms import GradeForm
from django.urls import reverse_lazy
from utils.permissions import RoleRequiredMixin

# Create your views here.


class GradeListView(RoleRequiredMixin,ListView):
    model = Grades
    template_name = 'grades/grades_list.html'
    fields = ['grade_name', 'grade_number']
    context_object_name = 'grades'  # 相当于我们在使用render()时传递的参数变量名称
    paginate_by = 10  # 分页显示的数量（即每一页显示多少数据）
    allowed_roles = ['admin']

    # 重写 get_queryset 方法，实现搜索功能
    def get_queryset(self):
        queryset = super().get_queryset()  # 保留调用原函数，获取所有的数据内容
        search = self.request.GET.get('search')  # 获取搜索的内容，在请求get的URL中获取search参数的值

        if search:  # 由于需要多项进行查询，因此使用Q函数
            queryset = queryset.filter(
                Q(grade_name__icontains=search) |
                Q(grade_number__icontains=search)
            )
        return queryset
        
class GradeCreateView(RoleRequiredMixin,CreateView):
    model = Grades
    template_name = 'grades/grade_form.html'
    form_class = GradeForm
    success_url = reverse_lazy('grade_list')  # 成功后跳转到哪个网址
    
class GradeUpdateView(RoleRequiredMixin,UpdateView):
    model = Grades
    template_name = 'grades/grade_form.html'
    form_class = GradeForm
    success_url = reverse_lazy('grade_list')
    
class GradeDeleteView(RoleRequiredMixin,DeleteView):
    model = Grades
    template_name = 'grades/grade_delete.html'
    success_url = reverse_lazy('grade_list')
    
    # 阻止删除
    def get(self, request, *args, **kwargs):
        current_user = request.user.username
        if current_user != 'admin':
            return JsonResponse({'status': 'error','messages': '此为测试管理员，没有删除权限！！！请自行返回界面继续操作'}, status=400,
                json_dumps_params={'ensure_ascii': False},  # 新增参数
                charset='utf-8' # 明确指定字符集
                )
        return super().get(request, *args, **kwargs)
    
